"""
自定义组件
1. 橡皮筋，带画笔事件，矩形，黄色，透明背景
2. 标签，带橡皮筋
"""
from PySide2.QtCore import Qt, QRect, QSize, QPoint
from PySide2.QtGui import QColor, QPen, QBrush, QPixmap, QPainter, QPalette
from PySide2.QtWidgets import QLabel, QRubberBand

class CRubberBand(QRubberBand):
    def __init__(self, QRubberBand_Shape, QWidget_parent=None):
        super(CRubberBand, self).__init__(QRubberBand_Shape, QWidget_parent)
        palette = QPalette()
        palette.setBrush(QPalette.WindowText, QBrush(Qt.red))
        self.setPalette(palette)

    def paintEvent(self, QPaintEvent):
        painter = QPainter(self)
        # 设置画笔颜色和大小
        pen_color = QColor(Qt.yellow)
        painter.setPen(QPen(pen_color, 2))
        # 透明背景
        brush_color = QColor(Qt.transparent)
        painter.setBrush(QBrush(brush_color))
        painter.drawRect(QPaintEvent.rect())

class CLabel (QLabel):
    def __init__(self, parentQWidget = None):
        super(CLabel, self).__init__(parentQWidget)
        self.initUI()

    def initUI (self):
        self.currentQRubberBand = CRubberBand(QRubberBand.Rectangle, self)

    def mousePressEvent (self, eventQMouseEvent):
        print('鼠标按压')
        self.myPoint = eventQMouseEvent.pos()
        self.currentQRubberBand.setGeometry(QRect(self.myPoint, QSize()))
        self.currentQRubberBand.show()

    def mouseMoveEvent (self, eventQMouseEvent):
        self.currentQRubberBand.setGeometry(QRect(self.myPoint, eventQMouseEvent.pos()).normalized())

    def mouseReleaseEvent (self, eventQMouseEvent):
        print('鼠标释放')
        # 缩放比=原始图像的宽度和高度/标签封闭矩形的宽度和高度
        orignalPix = QPixmap(self.pixmap())
        scaledX = orignalPix.width() / self.rect().width()
        scaledY = orignalPix.height() / self.rect().height()
        print("宽度缩放比: %d, 高度缩放比: %d" % (scaledX, scaledY))

        # 按压点处理
        upperLeftPoint = self.mapToGlobal(self.myPoint)
        print("按压点1：%d,%d" % (upperLeftPoint.x(), upperLeftPoint.y()))
        upperLeftPoint = self.mapFromGlobal(upperLeftPoint)
        print("按压点2：%d,%d" % (upperLeftPoint.x(), upperLeftPoint.y()))
        upperLeftPoint.setX(int(upperLeftPoint.x() * scaledX))
        upperLeftPoint.setY(int(upperLeftPoint.y() * scaledY))
        print("按压点3：%d,%d" % (upperLeftPoint.x(), upperLeftPoint.y()))

        # 释放点处理
        lowerRightPoint = eventQMouseEvent.globalPos()
        print("释放点1：%d,%d" % (lowerRightPoint.x(), lowerRightPoint.y()))
        lowerRightPoint = self.mapFromGlobal(lowerRightPoint)
        print("释放点2：%d,%d" % (lowerRightPoint.x(), lowerRightPoint.y()))
        lowerRightPoint.setX(int(lowerRightPoint.x() * scaledX))
        lowerRightPoint.setY(int(lowerRightPoint.y() * scaledY))
        print("释放点3：%d,%d" % (lowerRightPoint.x(), lowerRightPoint.y()))

        myRect = QRect(upperLeftPoint, lowerRightPoint)
        cropQPixmap = self.pixmap().copy(myRect)
        cropQPixmap.save('./resources/temp_CLabel.jpg')